package com.leanote.berial.tingphone.ui;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.widget.RadioGroup;

import com.leanote.berial.tingphone.R;
import com.leanote.berial.tingphone.base.BaseActivity;
import com.leanote.berial.tingphone.base.BaseFragment;
import com.leanote.berial.tingphone.ui.fragment.CustomListenPageFragment;
import com.leanote.berial.tingphone.ui.fragment.DownloadListenPageFragment;
import com.leanote.berial.tingphone.ui.fragment.DiscoverFragment;
import com.leanote.berial.tingphone.ui.fragment.PersonPageFragment;
import com.leanote.berial.tingphone.widget.NoScrollViewPager;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;

public class MainActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {

    @InjectView(R.id.rg_home)
    RadioGroup rg_home;

    @InjectView(R.id.vp_home)
    NoScrollViewPager vp_home;

    private List<BaseFragment> fragments;

    private HomeFragmentAdapter homeFragmentAdapter;


    @Override
    public void initView() {
        setContentView(R.layout.activity_main);

        ButterKnife.inject(this);

        initData();
    }

    private void initData() {

        fragments = new ArrayList<BaseFragment>();
        fragments.add(new DiscoverFragment());
        fragments.add(new CustomListenPageFragment());
        fragments.add(new DownloadListenPageFragment());
        fragments.add(new PersonPageFragment());

        homeFragmentAdapter = new HomeFragmentAdapter(getSupportFragmentManager());
        vp_home.setAdapter(homeFragmentAdapter);

        vp_home.setCurrentItem(0);
        vp_home.setOffscreenPageLimit(4);

        rg_home.check(R.id.rb_home_find);
        rg_home.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        int index = -1;
        switch (checkedId) {
            case R.id.rb_home_find:
                index = 0;
                break;
            case R.id.rb_home_custom_listen:
                index = 1;
                break;
            case R.id.rb_home_download_listen:
                index = 2;
                break;
            case R.id.rb_home_me:
                index = 3;
                break;
            default:
                break;
        }

        if (index != -1) {
            vp_home.setCurrentItem(index, false);
            fragments.get(index).initData();
        }
    }

    class HomeFragmentAdapter extends FragmentStatePagerAdapter {

        public HomeFragmentAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }
    }
}
